<script>
import { mapState } from 'vuex'

export default {
  name: 'deptForm',
  data() {
    const validateCode = (rule, value, callback) => {
      let dept = null
      if (this.formData.id) {
        dept = this.departmentsList.filter(item => item.id !== this.id).find(item => item.code === value)
      } else {
        dept = this.departmentsList.find(item => item.code === value)
      }
      dept ? callback(new Error(`部门编码${value}在${dept.name}已经存在`)) : callback()
    }
    const validateName = (rule, value, callback) => {
      let dept = null
      let parentDept = null
      if (this.formData.id) {
        dept = this.departmentsList.filter(item => item.pid === this.formData.pid && item.id !== this.formData.id).find(item => item.name === value)
        parentDept = this.departmentsList.find(item => item.id === dept?.pid)
      } else {
        dept = this.departmentsList.filter(item => item.pid === this.id).find(item => item.name === value)
        parentDept = this.departmentsList.find(item => item.id === dept?.pid)
      }
      dept ? callback(`部门名称${value}在${parentDept?.name || '公司'}已经存在`) : callback()
    }
    return {
      /* 表单数据对象 */
      formData: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        createTime: ''
      },
      /* 表单规则对象 */
      formRules: {
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '请选择部门创建日期', trigger: 'blur' }
        ]
      }
    }
  },
  props: {
    // 当前部门ID
    id: {
      type: String,
      required: true
    }
  },
  methods: {
    /* 派发action获取部门负责人的回调函数 */
    async fetchSimpleEmployees() {
      try {
        const message = await this.$store.dispatch('departmentsStore/fetchSimpleEmployees')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 点击部门负责人下拉框的回调函数调用fetchSimpleEmployees()派发action获取部门负责人 */
    handleClickSelect() {
      //如果已经有部门负责人列表了就return出去不执行下面逻辑
      if (this.persons.length) return
      this.fetchSimpleEmployees()
    },
    /* 派发action查询部门详情的回调函数 */
    async findDepartments(id) {
      try {
        const department = await this.$store.dispatch('departmentsStore/findDepartments', id)
        // 数据回显
        this.formData = department
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 派发action发送编辑部门的请求 */
    async doEdit() {
      try {
        const message = await this.$store.dispatch('departmentsStore/updateDepartments', this.formData)
        this.$message.success(message)
        this.$emit('submit')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 派发action发送添加部门的请求 */
    async doAdd() {
      try {
        // 整理带给服务的参数
        const params = { ...this.formData, pid: this.id }
        const message = await this.$store.dispatch('departmentsStore/addDepartments', params)
        this.$message.success(message)
        this.$emit('submit')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    /* 清空表单残留数据和重置表单的回调函数 */
    clearFormData() {
      this.formData = { code: '', introduce: '', manager: '', name: '', createTime: '' }
      this.$refs.elForm.resetFields()
    },
    /* 点击确定按钮的回调函数 */
    async handleSubmit() {
      const valid = await this.$refs.elForm.validate().catch(error => error)
      if (!valid) return
      if (this.formData.id) {
        // 调用doEdit()做发送编辑部门的请求
        this.doEdit()
      } else {
        // 调用doAdd()做发送添加部门的请求
        this.doAdd()
      }
    },
    /* 点击取消按钮的回调函数  */
    handleCancel() {
      this.$emit('cancel')
    }
  },
  computed: {
    ...mapState('departmentsStore', ['departmentsList', 'persons'])
  },
  emits: ['submit', 'cancel']
}
</script>

<template>
  <div class="deptForm">
    <el-form label-width="100px" ref="elForm" :model="formData" :rules="formRules">
      <el-form-item label="部门名称" prop="name">
        <el-input placeholder="请输入部门名称" v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input placeholder="请输入部门编码" v-model="formData.code"></el-input>
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="formData.manager" placeholder="请选择部门负责人" @click.native="handleClickSelect">
          <el-option v-for="(person,index) in persons" :value="person.username" :label="person.username" :key="person.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建日期" prop="createTime">
        <el-date-picker v-model="formData.createTime" type="date" placeholder="请选择部门创建日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input type="textarea" rows="4" resize="none" placeholder="请输入部门介绍" v-model="formData.introduce"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped lang="scss">
.el-select {
  width: 220px;
}
</style>
